﻿using DevExpress.Data.ExpressionEditor;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.WareHouseManage.WareHouseArea
{
    public partial class CreateAreaForm : DevExpress.XtraEditors.XtraForm
    {
        public CreateAreaForm()
        {
            InitializeComponent();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            //关闭当前弹窗
            this.Close();
        }

        public class AreaCreateModel
        {
            public string areaid { get; set; }
            public string areaname { get; set; }
            public string warehouseid { get; set; }
            public string areadesc { get; set; }
        }
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 获取用户输入 - 使用不同的控件
            string areaid = textEdit1.Text.Trim(); // 区域编码
            string areaname = textEdit4.Text.Trim(); // 区域名称
            string warehouseid = gridLookUpEdit1.EditValue?.ToString(); // 从下拉框获取仓库ID
            string areadesc = textEdit2.Text.Trim(); // 区域描述（假设使用MemoEdit）


            // 校验必要字段
            if (string.IsNullOrEmpty(areaid))
            {
                MessageBox.Show("区域编码不能为空");
                return;
            }
            if (string.IsNullOrEmpty(areaname))
            {
                MessageBox.Show("区域名称不能为空");
                return;
            }
            if (string.IsNullOrEmpty(warehouseid))
            {
                MessageBox.Show("所属仓库不能为空");
                return;
            }
            if (string.IsNullOrEmpty(areadesc))
            {
                MessageBox.Show("区域描述不能为空");
                return;
            }

            // 构造请求体对象
            var model = new AreaCreateModel
            {
                areaid = areaid,
                areaname = areaname,
                warehouseid = warehouseid,
                areadesc = areadesc
            };

            // 序列化为 JSON
            string jsonContent = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // 发起 POST 请求
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://39.103.49.30:9981/api/Area/CreateAREAMODEL", content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("保存成功！");
                        this.Close(); // 关闭当前窗口
                        //刷新当前页面
                        // 查找Form2的实例
                        WareHouseAreaForm form2 = Application.OpenForms.OfType<WareHouseAreaForm>().FirstOrDefault();
                        if (form2 != null)
                        {
                            form2.LoadDataFromApi(); // 调用Form2的方法
                        }
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"保存失败: {errorText}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }

        public class WarehouseModel
        {
            public string Id { get; set; }         // 必须与 ValueMember 一致
            public string WareHouseName { get; set; } // 必须与 DisplayMember 一致
        }

        public class ApiResult
        {
            public List<WarehouseModel> ResultData { get; set; }
        }

        private async void WareHouseAreaForm_Load(object sender, EventArgs e)
        {
            await LoadWarehousesAsync();
        }

        public async Task LoadWarehousesAsync()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://39.103.49.30:9981/api/WareHouseDefinition/GetWarehouseDefinitionIdAndName");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult>(json);

                        // 绑定数据到 GridLookUpEdit
                        gridLookUpEdit1.Properties.DataSource = result.ResultData;
                        gridLookUpEdit1.Properties.ValueMember = "Id";
                        gridLookUpEdit1.Properties.DisplayMember = "WareHouseName";

                        // 配置视图 - 这是关键修复点！
                        // 获取或创建 GridView
                        GridView view = gridLookUpEdit1.Properties.View as GridView;
                        if (view == null)
                        {
                            view = new GridView();
                            gridLookUpEdit1.Properties.View = view;
                        }

                        // 清除现有列
                        view.Columns.Clear();

                        // 添加列：仓库名称
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "WareHouseName",
                            Caption = "仓库名称",
                            Visible = true
                        });

                        // 添加列：仓库ID（可选）
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "Id",
                            Caption = "仓库ID",
                            Visible = false // 隐藏ID列
                        });

                        // 设置最佳列宽
                        view.BestFitColumns();

                        // 默认选中第一个
                        if (result.ResultData.Count > 0)
                            gridLookUpEdit1.EditValue = null;
                    }
                    else
                    {
                        MessageBox.Show("无法加载仓库信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
    }
}